package com.example.jwt.entity;


import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 实现 SpringSecurity 提供的 UserDetails 接口，保存登录信息
 */
@Data
public class LoginUser implements UserDetails {

    private User user;

    /** 权限集合 */
    private List<String> permissions;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    /** 防止 redis 存储 loginUser 时序列化出错 */
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    /** 用户的权限集，默认需要添加前缀 */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        //把 permissions 中 String 类型的权限信息封装成 SimpleGrantedAuthority 对象
        authorities = new ArrayList<>();
        for (String permission : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        return authorities;
    }

    /** 用户的加密后的密码，不加密会使用前缀 */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /** 应用内唯一的用户名 */
    @Override
    public String getUsername() {
        return user.getUsername();
    }

    /** 账户是否过期 */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /** 账户是否锁定 */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /** 凭证是否过期 */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /** 用户是否可用 */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
